/*
 * Copyright (c) 2006-2023, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2018-08-24     yangjie      the first version
 */

/*
 * 程序清单：互斥锁例程
 *
 * 互斥锁是一种保护共享资源的方法。当一个线程拥有互斥锁的时候，
 * 可以保护共享资源不被其他线程破坏。线程1对2个number分别进行加1操作
 * 线程2也会对2个number分别进行加1操作。使用互斥量保证2个number值保持一致
 */
#include <aos/aos.h>
#include "aos/cli.h"
#include <debug/dbg.h>

#define THREAD_PRIORITY         8
#define THREAD_TIMESLICE        5
#define THREAD_STACK_SIZE       2048

/* 指向互斥量的指针 */
static aos_mutex_t mutex = NULL;
static unsigned char number1, number2 = 0;

/* 线程控制块 */
static aos_task_t tid1 = NULL;
static aos_task_t tid2 = NULL;

static void rt_thread_entry1(void *parameter)
{
    while (1)
    {
        /* 线程1获取到互斥量后，先后对number1、number2进行加1操作，然后释放互斥量 */
        aos_mutex_lock(&mutex, AOS_WAIT_FOREVER);
        number1++;
        aos_msleep(10);
        number2++;
        aos_mutex_unlock(&mutex);
    }
}

static void rt_thread_entry2(void *parameter)
{
    while (1)
    {
        /* 线程2获取到互斥量后，检查number1、number2的值是否相同，相同则表示mutex起到了锁的作用 */
        aos_mutex_lock(&mutex, AOS_WAIT_FOREVER);
        if (number1 != number2)
        {
            aos_debug_printf("not protect.number1 = %d, mumber2 = %d \n", number1, number2);
        }
        else
        {
            aos_debug_printf("mutex protect ,number1 = mumber2 is %d\n", number1);
        }

        number1++;
        number2++;
        aos_mutex_unlock(&mutex);

        if (number1 >= 50)
            return;
    }
}

/* 互斥量示例的初始化 */
int yoc_mutex_sample(int argc, char **argv)
{
    int result;
    /* 创建一个互斥量 */
    result = aos_mutex_new(&mutex);

    if(result != 0)
    {
        aos_debug_printf("create dynamic mutex failed.\n");
        return -1;
    }

    aos_task_create(&tid1,
                    "thread1",
                    rt_thread_entry1, NULL,
                    NULL,
                    THREAD_STACK_SIZE,
                    THREAD_PRIORITY,
                    AOS_TASK_AUTORUN);

    aos_task_create(&tid2,
                    "thread2",
                    rt_thread_entry2, NULL,
                    NULL,
                    THREAD_STACK_SIZE,
                    THREAD_PRIORITY -1,
                    AOS_TASK_AUTORUN);

    return 0;
}

ALIOS_CLI_CMD_REGISTER(yoc_mutex_sample, yoc_mutex_sample,yoc mutex sample);
